import React, { useEffect, useState } from 'react';
import { FieldProps } from '@rjsf/utils';
import { Switch } from 'antd';
type SwitchArrType = { [key: string]: boolean };
// 选择器
export const SwitchArr = ({
  schema,
  onChange,
  uiSchema,
  disabled,
}: FieldProps<SwitchArrType>) => {
  const selectList = (uiSchema['ui:options']?.options as Array<any>) ?? [];
  const disabledBoolean = disabled
    ? disabled
    : (uiSchema['ui:disabled'] ?? false);
  const [switchArr, setSwitchArr] = useState<SwitchArrType>({});
  useEffect(() => {
    setSwitchArr(schema.default as SwitchArrType);
  }, [schema]);
  const change = (key, value) => {
    setSwitchArr((state) => {
      const res = { ...state, [key]: value };
      onChange(res);
      return res;
    });
  };
  const style = { gap: '5px' };
  return (
    <div
      className='flex'
      style={style}>
      {selectList.map((item) => (
        <div
          className='flex items-center fs'
          style={style}>
          <Switch
            size='small'
            checked={switchArr?.[item.const]}
            onChange={(value) => change(item.const, value)}
            disabled={
              disabledBoolean ||
              isdis(selectList, item?.relyon, switchArr) ||
              item?.disabled ||
              disabled
            }
          />
          {item.title}
        </div>
      ))}
    </div>
  );
};

function isdis(selectList, relyon: string | string[], switchArr) {
  if (!relyon) {
    return false;
  }
  if (!Array.isArray(relyon)) {
    relyon = [relyon];
  }
  const key = selectList.find((i) => relyon.includes(i?.const))?.const;
  return relyon ? !switchArr[key] : false;
}

/**
 * @deprecated 这是一个switch开关组
 * @example 
 * schema: {
  SwitchArr: {
    type: 'object',
    default: {
      Perview: true,
      DirectEdit: false, 
    } 
  } 
 }
 * uiSchema: {
   'ui:FieldTemplate': SwitchArr,
    'ui:options': {
      options: [
        {
          const: 'Perview',
          title: 'Perview',
        },
        {
          const: 'DirectEdit',
          title: 'Direct Edit',
          relyon: 'Perview', // 依赖于Perview 即Perview为true时才可以使用
        },
      ],
    },
 }
 * */
